﻿using AlibabaCloud.SDK.VIAPI.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AliYun_RenLian_Obj
{
    public partial class Ren_LianModel : UserControl
    {
        //匹配失败次数累计
        int number = 0;
        private Form1 form1;
        private string clbhk;
        private string setclmc;
        private string km;
        private string wldz;
        private string cID;
        private string dID;
        private string HYXM;
        private string djh;
        private string HYBH;
        private string lch;
        private string profile_picture;

        public Ren_LianModel()
        {
            InitializeComponent();
        }

        private System.Threading.Timer timer;
        public string filePath = "";
        public Ren_LianModel(Form1 form1, string clbhk, string setclmc, string km, string wldz, string cID, string dID, string lch)
        {
            InitializeComponent();
            this.form1 = form1;
            this.clbhk = clbhk;
            this.setclmc = setclmc;
            this.km = km;
            this.wldz = wldz;
            this.cID = cID;
            this.dID = dID;
            this.lch = lch;
            string time_jg = System.Configuration.ConfigurationManager.ConnectionStrings["time_jg"].ConnectionString.ToString();
            string filePath = System.Configuration.ConfigurationManager.ConnectionStrings["filePath"].ConnectionString.ToString();

            this.filePath = filePath;

            this.timer2.Interval = int.Parse(time_jg);
            this.timer2.Start();
            Tou_Txt(this.label1.Text = "车辆编号：" + this.clbhk + " 科目：" + this.km + " 车型：" + this.clbhk);
        }


        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void timer2_Tick(object sender, EventArgs e)
        {

        }

        private void Log(string message)
        {
            if (txtLog.InvokeRequired)
            {
                txtLog.Invoke(new Action<string>(Log), new object[] { message });
            }
            else
            {
                txtLog.AppendText($"{DateTime.Now}: {message}\r\n\r\n");
                txtLog.ScrollToCaret();
            }
        }
        private void Tou_Txt(string message)
        {
            if (label1.InvokeRequired)
            {
                label1.Invoke(new Action<string>(Tou_Txt), new object[] { message });
            }
            else
            {

            }
        }
        public string z_url(string path_url)
        {
            try
            {
                string OSS_AccessKeyId = System.Configuration.ConfigurationManager.ConnectionStrings["RenLian_AccessKeyId"].ConnectionString.ToString();
                string OSS_AccessKeySecret = System.Configuration.ConfigurationManager.ConnectionStrings["RenLian_AccessKeySecret"].ConnectionString.ToString();

                // 场景一，使用本地文件
                //string file = ConvertBase64ToImageAndSave(profile_picture, HYBH);
                // 场景二，使用任意可访问的url
                //string file = "https://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024";
                // 创建AccessKey ID和AccessKey Secret，请参考https://help.aliyun.com/document_detail/175144.html。
                // 如果您用的是RAM用户的AccessKey，还需要为RAM用户授予权限AliyunVIAPIFullAccess，请参考https://help.aliyun.com/document_detail/145025.html。
                // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行示例前必须先配置环境变量。
                FileUtils fileobj = FileUtils.getInstance(Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
                //FileUtils fileobj = FileUtils.getInstance(OSS_AccessKeyId, OSS_AccessKeySecret);
                string ossUrl = fileobj.Upload(path_url);
                //return ossUrl;
                return ossUrl;
            }
            catch (Exception)
            {
                return "";
            }

        }
        int yc_count = 0;
        private async Task main_zxAsync()
        {
            this.timer2.Stop();
            string Confidence = System.Configuration.ConfigurationManager.ConnectionStrings["Confidence"].ConnectionString.ToString();
            string Pic_Url = System.Configuration.ConfigurationManager.ConnectionStrings["Pic_Url"].ConnectionString.ToString();
            string zt_number = System.Configuration.ConfigurationManager.ConnectionStrings["zt_number"].ConnectionString.ToString();
            string time_stop = System.Configuration.ConfigurationManager.ConnectionStrings["time_stop"].ConnectionString.ToString();
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    string path_url = "";
                    string Post_Url = $"{Pic_Url}?did={this.dID}&cid={this.cID}";
                    HttpResponseMessage response = await client.GetAsync(Post_Url);

                    if (response.IsSuccessStatusCode)
                    {
                        string save_url = "";
                        string responseBody = await response.Content.ReadAsStringAsync();
                        var obj = JsonConvert.DeserializeObject<des_obj>(responseBody);


                        //// 发送 HEAD 请求检查资源状态
                        //HttpResponseMessage headResponse = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, obj.url));
                        //if (headResponse.IsSuccessStatusCode)
                        //{
                        Log("\r\n\r\n" + DateTime.Now.ToShortTimeString() + " 成功获取到摄像图片链接" + obj.url);

                        byte[] imageBytes = new byte[0];
                        int cs_count = 0;
                        bool success = true;
                        while (success)
                        {
                            if (cs_count >= int.Parse(time_stop))
                            {
                                success = false;
                                break; // 下载成功，退出重试循环
                            }
                            cs_count++;
                            try
                            {
                                imageBytes = await client.GetByteArrayAsync(obj.url); // 下载图片数据到字节数组
                                save_url = Guid.NewGuid().ToString() + ".png";
                                string url_pan = this.filePath + save_url;
                                path_url = url_pan;
                                // 将字节数组保存到本地文件
                                File.WriteAllBytes(url_pan, imageBytes);

                                success = false;
                                break; // 下载成功，退出重试循环
                            }
                            catch (Exception ex)
                            {
                                Log("\r\n\r\n" + DateTime.Now.ToShortTimeString() + $"下载失败，重试第 ({cs_count})次: {ex.Message}");
                                await Task.Delay(2000); // 等待 2 秒后重试

                            }
                        }



                        string base64String = Convert.ToBase64String(imageBytes); // 将字节数组转换为 Base64 字符串
                                                                                 

                        #region 将摄像头传递的图片显示出来
                        // 使用 MemoryStream 将字节数组转换为 Image 对象
                        using (MemoryStream ms = new MemoryStream(imageBytes))
                        {
                            Image image = Image.FromStream(ms);

                            // 将 Image 对象显示在 PictureBox 控件中
                            pictureBox2.Image = image;
                        }
                        #endregion
                        string RenLianDb_Name = System.Configuration.ConfigurationManager.ConnectionStrings["RenLianDb_Name"].ConnectionString.ToString();

                        string Limit = System.Configuration.ConfigurationManager.ConnectionStrings["Limit"].ConnectionString.ToString();
                        string QualityScoreThreshold = System.Configuration.ConfigurationManager.ConnectionStrings["QualityScoreThreshold"].ConnectionString.ToString();
                        string MaxFaceNum = System.Configuration.ConfigurationManager.ConnectionStrings["MaxFaceNum"].ConnectionString.ToString();
                        //Sample_RES_HTTP sample_RES_HTTP = new Sample_RES_HTTP();
                        //var res_http = sample_RES_HTTP.Main2(path_url);
                        string http_url = z_url(path_url);
                        Sample_SouSuo sample_SouSuo = new Sample_SouSuo(); 
                        var res_data = sample_SouSuo.Main(http_url, RenLianDb_Name, int.Parse(Limit), float.Parse(QualityScoreThreshold), int.Parse(MaxFaceNum));

                        if (res_data.code == 0)
                        {
                            //string str = " insert into RenLian_JS(ID,clbh,HYBH,HYXM,XiangSiDu,ZhuangTai,FaShengShiJian,YiChangYuanYin,PIC) values('" + Guid.NewGuid().ToString() + "','"
                            // + this.clbhk + "','','','0','异常',getdate(),'" + res_data.Message + "',''  ); ";

                            //Updatedata(str);
                            Log($"\r\n\r\n" + DateTime.Now.ToShortTimeString() + res_data.Message);
                        }
                        else
                        if (res_data.data.Count() > 0)//不为空，代表有匹配到人脸(但是不一定有合适的)
                        {

                            #region 20250520
                            string str = "";
                            var rl_obj = res_data.data.OrderByDescending(t => t.Confidence).FirstOrDefault();
                            var data_count = rl_obj.Confidence ?? 0;
                            if (data_count >= float.Parse(Confidence))
                            {
                                yc_count = 0;
                                number = 0;
                                string time_jg = System.Configuration.ConfigurationManager.ConnectionStrings["time_jg"].ConnectionString.ToString();

                                this.timer2.Interval = int.Parse(time_jg);
                                str += " insert into RenLian_JS(ID,clbh,HYBH,HYXM,XiangSiDu,ZhuangTai,FaShengShiJian,YiChangYuanYin,PIC,this.lch) values('" + Guid.NewGuid().ToString() + "','"
                                     + this.clbhk + "','" + rl_obj.EntityId + "','" + rl_obj.ExtraData + "','" + rl_obj.Confidence + "','正常',getdate(),'','" + save_url + " ','" + this.lch + " '  ); ";
                                Updatedata(str);
                                Log($"\r\n\r\n" + DateTime.Now.ToShortTimeString() + res_data.Message);
                            }
                            else
                            {
                                yc_count++;
                                string time_cw_jg = System.Configuration.ConfigurationManager.ConnectionStrings["time_cw_jg"].ConnectionString.ToString();
                                string PhoneNumbers = System.Configuration.ConfigurationManager.ConnectionStrings["PhoneNumbers"].ConnectionString.ToString();
                                string TemplateCode = System.Configuration.ConfigurationManager.ConnectionStrings["TemplateCode"].ConnectionString.ToString();

                                this.timer2.Interval = int.Parse(time_cw_jg);

                                number++;
                                if (number >= int.Parse(zt_number))//达到设定次数后暂停练车
                                {
                                    number = 0;
                                    yc_count = 0;
                                    string time_jg = System.Configuration.ConfigurationManager.ConnectionStrings["time_jg"].ConnectionString.ToString();

                                    this.timer2.Interval = int.Parse(time_jg);

                                    //if (data_count < float.Parse(Confidence))
                                    //{
                                        str += " insert into RenLian_JS(ID,clbh,HYBH,HYXM,XiangSiDu,ZhuangTai,FaShengShiJian,YiChangYuanYin,PIC,lch) values('" + Guid.NewGuid().ToString() + "','"
                                      + this.clbhk + "','" + rl_obj.EntityId + "','" + rl_obj.ExtraData + "','" + rl_obj.Confidence + "','异常',getdate(),'','" + save_url + " ','" + this.lch + " '  ); ";
                                        Updatedata(str);
                                        Sample_DuanXin sample_DuanXin = new Sample_DuanXin();
                                        var dx_res= sample_DuanXin.Main2(this.lch, PhoneNumbers, TemplateCode);
                                     
                                            Log($"\r\n\r\n" + DateTime.Now.ToShortTimeString() + "短信发送信息：" + dx_res.Message);

                                    //}


                                    this.txtLog.Text = "";

                                }
                                Log($"\r\n\r\n" + DateTime.Now.ToShortTimeString() + " 车辆编号为" + this.clbhk + ",没有匹配到会员的人脸第 (" + yc_count + ")次!人脸比对信息： " + res_data.Message);

                            }
                            #endregion


                            Updatedata(str);
                            Log($"\r\n\r\n" + DateTime.Now.ToShortTimeString() + res_data.Message);
                        }
                        else//为空，代表没有匹配到人脸
                        {

                        }
                    }
                    else
                    {
                        Log("\r\n\r\n获取车内摄像信息失败: " + JsonConvert.SerializeObject(response));
                    }
                }
                catch (HttpRequestException e)
                {
                    Log("\r\n\r\n获取车内摄像信息异常: " + e.Message);
                }
                finally
                {
                    SomeBackgroundMethod();
                }
            }

        }
        private void SomeBackgroundMethod()
        {
            // 错误：直接在后台线程启动可能无效
            // this.timer2.Start();

            // 正确：使用Invoke确保在UI线程中执行
            this.Invoke(new Action(() =>
            {
                this.timer2.Start();
            }));
        }
        public static DataTable GetDataSet(string safeSql)
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["datebase"].ConnectionString.ToString();
            try
            {
                DataSet ds = new DataSet();
                SqlCommand cmd = new SqlCommand(safeSql, con);
                cmd.CommandTimeout = 3000;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("连接超时时间已到"))
                {
                    MessageBox.Show("连接服务器超时！", "提示");
                    return null;
                }
                else
                {
                    throw ex;
                }

            }
            finally
            {
                if (con != null && con.State == System.Data.ConnectionState.Open)
                {
                    con.Close();
                }
                else if (con != null && con.State == System.Data.ConnectionState.Broken)
                {
                    con.Close();
                }
            }
        }

        /// <summary>
        /// 执行增删改语句
        /// </summary> 
        /// <param name="tablename"></param>
        public static void Updatedata(string sql)
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["datebase"].ConnectionString.ToString();
            con.Open();
            //SqlConnection con = COMMON.Con;
            SqlCommand com = new SqlCommand();
            com.Connection = con;
            com.CommandType = CommandType.Text;
            com.CommandText = sql;
            SqlDataReader dr = com.ExecuteReader();//执行SQL语句
            dr.Close();
            con.Close();
        }
        public class des_obj
        {
            public string url { get; set; }
        }

        private void txtLog_TextChanged(object sender, EventArgs e)
        {

        }

        //private void timer2_Tick(object sender, EventArgs e)
        //{

        //try
        //{
        //    DataTable dt = GetDataSet($" select * from  (select gmdata.*,HYXXB.HYXM,HYXXB.profile_picture,HYXXB.CX_HY,(select is_rldb from FWLX where fwlx_name=gmdata.fwlx) as is_rldb from gmdata left join HYXXB on gmdata.HYBH=HYXXB.HYBH) b where (b.syzt='使用中' or b.syzt='已暂停') and b.is_rldb='是' and b.wldz='{this.wldz}'   ");

        //    if (dt.Rows.Count > 0)
        //    {
        //        this.profile_picture = dt.Rows[0]["profile_picture"].ToString().Trim();
        //        this.HYXM = dt.Rows[0]["HYXM"].ToString().Trim();
        //        this.djh = dt.Rows[0]["djh"].ToString().Trim();
        //        this.HYBH = dt.Rows[0]["HYBH"].ToString().Trim();
        //        if (!string.IsNullOrEmpty(this.profile_picture))
        //        {
        //            if (!this.timer2.Enabled)
        //            {
        //                this.timer2.Start();
        //            }



        //            // 将 Base64 字符串转换为字节数组
        //            byte[] imageBytes = Convert.FromBase64String(this.profile_picture);

        //            // 使用 MemoryStream 将字节数组转换为 Image 对象
        //            using (MemoryStream ms = new MemoryStream(imageBytes))
        //            {
        //                Image image = Image.FromStream(ms);

        //                // 将 Image 对象显示在 PictureBox 控件中
        //                pictureBox1.Image = image;
        //            }
        //        }
        //        else
        //        {
        //            pictureBox1.Image = null;
        //            this.timer2.Stop();
        //        }
        //        Tou_Txt(this.label1.Text = "车辆编号：" + this.clbhk + " 科目：" + this.km + " 车型：" + this.clbhk + " 会员姓名：" + this.HYXM + " 订单号：" + this.djh);

        //    }
        //    else
        //    {
        //        Tou_Txt(this.label1.Text = "车辆编号：" + this.clbhk + " 科目：" + this.km + " 车型：" + this.clbhk);


        //    }



        //}
        //catch (Exception)
        //{

        //}

        //}

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // _ = main_zxAsync();
        }

        private void txtLog_TextChanged_1(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //string RenLianDb_Name = System.Configuration.ConfigurationManager.ConnectionStrings["RenLianDb_Name"].ConnectionString.ToString();
            //Sample_SouSuo sample = new Sample_SouSuo();
            //var res_data = sample.Main(RenLianDb_Name);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string RenLianDb_Name = System.Configuration.ConfigurationManager.ConnectionStrings["RenLianDb_Name"].ConnectionString.ToString();

            Sample_Create_Db sample = new Sample_Create_Db();
            var res_data = sample.Main(RenLianDb_Name);
        }

        private void timer2_Tick_1(object sender, EventArgs e)
        {

            Task.Run(async () =>
            {
                main_zxAsync();
            });
            //this.backgroundWorker1.RunWorkerAsync();

        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
